package com.xunmall.gateway.security;

import com.google.common.collect.Sets;
import com.xunmall.account.dto.LoginUserDto;
import com.xunmall.account.dto.RoleDto;
import com.xunmall.account.service.RoleRemoteService;
import com.xunmall.account.service.UserRemoteService;
import com.xunmall.base.dto.Result;
import com.xunmall.security.SecUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 *
 * @author Gimgoog
 * @date 2017/11/17
 */
@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRemoteService userRemoteService;
    @Autowired
    private RoleRemoteService roleRemoteService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<LoginUserDto> req = userRemoteService.getByUserName(username);
        if(!req.getSuccess()){
            log.warn("getByUserName error:" + req.getMessage());
        }
        LoginUserDto user = req.getData();

        if (user == null) {
            throw new UsernameNotFoundException("用户" + username + " 不存在");
        }

        //  obtainGrantedAuthorities(user);
        Collection<GrantedAuthority> grantedAuths = Sets.newHashSet();

        boolean enabled = user.getEnabled() == null ? true : user.getEnabled();
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = enabled;

        SecUser userdetails = new SecUser(user.getUuid(), user.getMobile(), user.getPassword(), user.getSalt(), user.getUsername(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

        return userdetails;
    }

    /**
     * 获得用户所有角色的权限集合.
     */
	private Collection<GrantedAuthority> obtainGrantedAuthorities(LoginUserDto user) {
		Collection<GrantedAuthority> authSet = Sets.newHashSet();
		Result<List<RoleDto>> req = roleRemoteService.getByUser(user.getUuid(),user.getCompUuid());
		if(!req.getSuccess()) {
		    log.warn("getRoles error:" + req.getMessage());
        }
		List<RoleDto> roles = req.getData();
		for (RoleDto role : roles) {
			authSet.add(new SimpleGrantedAuthority(role.getRoleCode()));
		}
		return authSet;
	}
}
